import { ADD_TODO, DELETE_TODO, EDIT_TODO, TOGGLE_TODO } from "./action";

export type Todo = {
    id: number,
    text: string,
    isCompleted: boolean
}

type Action =
    | { type: typeof ADD_TODO; payload: { id: number, text: string } }
    | { type: typeof DELETE_TODO; payload: { id: number } }
    | { type: typeof TOGGLE_TODO; payload: { id: number } }
    | { type: typeof EDIT_TODO; payload: { id: number, text: string } }

const initialState: Todo[] = [
    {
        "id": 1,
        "text": "Shopping",
        "isCompleted": false
    },
    {
        "id": 2,
        "text": "Cooking",
        "isCompleted": true
    },
    {
        "id": 3,
        "text": "Coding",
        "isCompleted": false
    }
]

export const todoReducer = (state = initialState, action: Action): Todo[] => {
    switch (action.type) {
        case "ADD_TODO":
            return [...state, { id: action.payload.id, text: action.payload.text, isCompleted: false }]
        case "DELETE_TODO":
            return state.filter(todo => todo.id !== action.payload.id)
        case "TOGGLE_TODO":
            return state.map(todo =>
                todo.id === action.payload.id ? { ...todo, isCompleted: !todo.isCompleted } : todo
            );
        case "EDIT_TODO":
            return state.map(todo =>
                todo.id === action.payload.id ? { ...todo, text: action.payload.text } : todo
            )
        default:
            return state;
    }
}